<template>
  <div class="XFiles">
    <el-upload
      ref="XFiles"
      :action="action"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      :on-remove="onRemove"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :accept="attrs.accept"
      :data="attrs.data"
      :limit="attrs.limit"
      :on-exceed="handleExceed"
      :file-list="fileList">
      <i class="el-icon-plus" />
      <div slot="file" slot-scope="{file}">
        <el-image v-if="file.url.indexOf('blob') > -1" :preview-src-list="[file.url]" class="el-upload-list__item-thumbnail" :src="file.url" />
        <el-image v-else class="el-upload-list__item-thumbnail" :src="attrs.urlPrefix ? attrs.urlPrefix + file.url : file.url" />
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in" />
          </span>
          <span
            v-if="attrs.isDownload"
            class="el-upload-list__item-delete"
            @click="handleDownload(file)">
            <i class="el-icon-download" />
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)">
            <i class="el-icon-delete" />
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog title="图片预览" :visible.sync="dialogVisible" :modal="false">
      <el-image width="100%" :src="dialogImageUrl">
        <div slot="error" class="image-slot">
          <i class="el-icon-picture" />
          404
        </div>
      </el-image>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import XMixIn from './XMixIn'
export default {
  mixins: [XMixIn],
  watch: {
    dataValue: function (val) {
      if (val.length === 0) {
        this.fileList = []
        let refStyle = this.$refs.XFiles.$el.style
        refStyle.setProperty('--displayVal', 'inline-block')
      } else if (val.length === this.attrs.limit) {
        let refStyle = this.$refs.XFiles.$el.style
        refStyle.setProperty('--displayVal', 'none')
      }
    }
  },
  data () {
    return {
      fileList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      isDel: false
    }
  },
  props: {
    action: {
      type: [String],
      default: '/'
    }
  },
  mounted () {
    this.$nextTick(function () {
      if (this.attrs.width === undefined) { this.attrs.width = '80px' }
      if (this.attrs.height === undefined) { this.attrs.height = '80px' }
      let refStyle = this.$refs.XFiles.$el.style
      refStyle.setProperty('--widthVal', this.attrs.width)
      refStyle.setProperty('--heightVal', this.attrs.height)
      if (this.dataValue) {
        this.dataValue.forEach(element => {
          this.fileList.push(element)
        })
      }
    })
  },
  methods: {

    /** 请求前 */
    beforeAvatarUpload (file) {
      if (this.attrs.sizeMax !== undefined && typeof this.attrs.sizeMax === 'number' && file.size / 1024 > this.attrs.sizeMax) {
        this.$message.error(`上传失败, 当前限制最大 ${Math.round(this.attrs.sizeMax / 1024)} M`)
        this.isDel = true
        return false
      }

      if (this.attrs.sizeMin !== undefined && typeof this.attrs.sizeMin === 'number' && file.size / 1024 < this.attrs.sizeMin) {
        this.$message.error(`上传失败, 当前限制最小 ${Math.round(this.attrs.sizeMin / 1024)} M`)
        this.isDel = true
        return false
      }

      if (this.attrs.accept !== undefined && this.attrs.isAccept !== undefined) {
        let acceptArr = this.attrs.accept.split(',')
        if (this.attrs.isAccept) {
          let selectIndex = acceptArr.indexOf(file.type)
          if (selectIndex === -1) {
            this.$message.error('上传失败, 该文件不符合限制格式')
            this.isDel = true
            return false
          }
        }
      }
    },
    handleExceed (file) {
      this.$message.error(`上传失败, 当前限制选择 ${this.attrs.limit} 个文件`)
    },
    handleAvatarSuccess (res, file) {
      if (this.attrs.resultKey === undefined) {
        this.attrs.resultKey = 'url'
      }
      this.dataValue.push({
        name: file.raw.name,
        url: file.response[this.attrs.resultKey],
        size: file.raw.size,
        type: file.raw.type
      })
      this.valueChange(this.dataValue)
      if (this.attrs.limit !== undefined && this.attrs.limit === this.dataValue.length) {
        let refStyle = this.$refs.XFiles.$el.style
        refStyle.setProperty('--displayVal', 'none')
      }
    },
    handleRemove (file, fileList) {
      if (!this.isDel) {
        this.$confirm('您确定要删除该文件吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.onRemove(file, fileList)
        })
      }
    },
    onRemove (file, fileList) {
      if (!this.isDel) {
        let selectIndex = this.dataValue.findIndex(item => item.uid === file.uid)
        this.dataValue.splice(selectIndex, 1)
        this.valueChange(this.dataValue)
        let refStyle = this.$refs.XFiles.$el.style
        refStyle.setProperty('--displayVal', 'inline-block')
        this.$message.success('操作成功')
      } else {
        this.isDel = false
      }
    },
    handleDownload () {},
    handlePictureCardPreview (file) {
      // console.log(event.target.parentNode.parentNode.parentNode.childNodes[2].childNodes)
      // document.querySelector('#XElImage').click()
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    }
  }
}
</script>
<style>
.XFiles {
  --widthVal: 80px;
  --heightVal: 80px;
  --displayVal: inline-block;
}
.XFiles /deep/ .el-upload--picture-card {
  width: var(--widthVal) !important;
  height: var(--heightVal) !important;
  line-height: var(--heightVal) !important;
}
.XFiles /deep/ .el-upload-list--picture-card .el-upload-list__item {
  width: var(--widthVal) !important;
  height: var(--heightVal) !important;
}
.XFiles /deep/ .el-upload{
  display: var(--displayVal) !important;
}
</style>
